package com.itheima.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.itheima.gateway.util.AuthProperties;
import com.itheima.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@RequiredArgsConstructor
@Component
public class AuthGlobalFilter implements GlobalFilter {
    private final AuthProperties authProperties;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (isAllowPath(request)) {
           return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst("authorization");
        Long userId = null;
        if (StrUtil.isEmpty(authorization) || ((userId = jwtTool.parseToken(authorization)) == null)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录\"}".getBytes(StandardCharsets.UTF_8))));
        }

        String userInfo = userId.toString();
        exchange.mutate().request(builder -> builder.header("user-info", userInfo));

        return chain.filter(exchange);
    }

//    public boolean isExcludePaths(String path) {
//        List<String> excludePaths = authProperties.getExcludePaths();
//        AntPathMatcher antPathMatcher = new AntPathMatcher();
//        return excludePaths.stream().anyMatch(excludePath -> antPathMatcher.match(excludePath, path));
//    }


    private boolean isAllowPath(ServerHttpRequest request) {
        boolean flag = false;
        // 1.获取当前路径
        // String method = request.getMethodValue();
        String path = request.getPath().toString();
        // 2.要放行的路径
        for (String excludePath : authProperties.getExcludePaths()) {
            boolean isMatch = pathMatcher.match(excludePath, path);
            if (isMatch) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
